package com.neusoft.dibuy.th;

public class MyTickets {

    public static void main(String[] args) {
        Account account = new Account();
        Thread thread1 = new TicketAccount(account);
        Thread thread2 = new TicketAccount(account);
        thread1.start();
        thread2.start();

    }
    public static void main1(String[] args) {
        Thread thread = new Ticket();
        thread.setName("窗口一： ");
        thread.start();
        Thread thread2 = new Ticket();
        thread2.setName("窗口二： ");
        thread2.start();
    }

}

class TicketAccount extends   Thread {
    private Account account;
    public TicketAccount(Account account) {
        this.account = account;
    }

    public void run() {
        while (true) {
            account.qu();
            if (account.getBalance() <=0 )
                break;
        }
    }

}

class Ticket extends Thread {
    private static int num = 10;

    public  synchronized void run1() {
        while (true) {
//            锁一个代码片段
//            synchronized("abc") {
            if (num > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "正在出售第" + num-- + "张票");
            } else {
                System.out.println("票卖完了");
                break;
            }
//            }

        }
    }

    /**
     * TODO :范围
     */
    public void run() {
        run1();
    }
}
class Account {
    private int balance = 1000;

    public int getBalance() {
        return balance;
    }

    public  synchronized void qu(){ // 同步方法
        if(balance>=1000){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            balance -= 1000;
            System.out.println("取了1000元，balance = " + balance);
        }
    }
}